package Twitter.Listener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;


import org.apache.log4j.BasicConfigurator;
/*********************************************************
 * The class is designed for gracefully shut down a server
 * It implements Runnable interface
 * It listens the input of the user, if the input is equal to "--shutdown",then it will shut down the server socket .
 * @author fang
 *
 */
public class ShutDownListener implements Runnable{
	private ServerSocket serverSocket;
	private ExecutorService threadPool;
	private RequestListener listener;
	/*********************************************************************
	 * Class contructor
	 * @param serverSocket:specify which server socket is going to be shut down.
	 * @param threadPool:specify which thread pool is going to be shut down.
	 * @param listener:specify which RequestListener is goint to be shut down.
	 */
	public ShutDownListener(ServerSocket serverSocket,ExecutorService threadPool,RequestListener listener)
	{
		this.serverSocket=serverSocket;
		BasicConfigurator.configure();
		this.threadPool=threadPool;
		this.listener=listener;
	}
	/****************************************************************
	 * listens for the input of the user
	 * if the input equals "--shutdown" ,then it will gracefully shutdown the server
	 */
	public void run()
	{
		 BufferedReader stdin = new BufferedReader
	      (new InputStreamReader(System.in));
	    String message=""; // Creates a varible called message for input
		while(true)
		{
	
			    try {
			    	if(stdin!=null)
			    	{
			    		message = stdin.readLine();
			    		if(message!=null)
			    		{
			    			
			    			if( message.trim().equals("--shutdown"))
							{
								closeSocket();
								this.threadPool.shutdownNow();
								listener.shutdown();
							
								System.out.println("the server has been shutdown");
								break;
							}
			    			
			    			if(!message.equals(""))
			    			{
			    				System.out.println("not shutdown");
			    			}
			    			
			    		}
						
			    	}
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}
	/*********************************************************
	 * close the ServerSocket
	 */
	private  void closeSocket() {
		try {
			this.serverSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
